package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BitmapUtils;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.FileUtil;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.view.DeleteImageView;
import com.eeepay.eeepay_v2.view.FlowLayout;
import com.eeepay.v2_library.dialog.CustomDialog;
import com.eeepay.v2_library.dialog.DialogUtil;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.view.TitleBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.ProblemApiServiceGrpc;
import cn.eeepay.api.grpc.nano.ProblemProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/15 0015.
 * 问题求助
 */
public class ProblemHelpActivity extends ABPhotoActivity implements View.OnClickListener, DeleteImageView.OnDeleteClickListener {

    private final int COMMIT_PROBLEM = 2;
    private final int PROBLEM_TYPE = 1;// add by zhuangzeqin 2017年4月19日09:05:18 问题类型

    //    private HorizontalItemView hv_sort;// 类别
//    private LabelEditText et_title; //标题
    private EditText et_content; // 内容
    private FlowLayout fLayout_img; //放置图片的自动布局
    private RelativeLayout rl_addImage;//添加图片
    private Button btn_confirm; // 提交

    private String typeName, typeId;//问题类型名字，ID
    private List<String> filePaths;
    private int i;//统计图片的数量

    private RadioGroup ll_marklayout;//动态添加标签
    //温馨提示框
    private CustomDialog exitDialog;

    private TitleBar title_bar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_problem_help;
    }

    @Override
    protected void initWidget() {
//        hv_sort = getViewById(R.id.hv_problem_sort);
//        et_title = getViewById(R.id.et_title);
        et_content = getViewById(R.id.et_content);
        fLayout_img = getViewById(R.id.layout_image);
        rl_addImage = getViewById(R.id.rl_add_image);
        btn_confirm = getViewById(R.id.btn_confirm);
        ll_marklayout = getViewById(R.id.ll_marklayout);
        title_bar = getViewById(R.id.title_bar);
        sendHttpRequest(PROBLEM_TYPE);
        filePaths = new ArrayList<>();
    }

    private void initMarksView(ProblemProto.ProblemTypeMsg[] problemTypes) {
        //添加标签内容
        for (int i = 0; i < problemTypes.length; i++) {
        /*    RadioButton tempButton = new RadioButton(mContext);
            tempButton.setBackgroundResource(R.drawable.into_pieces_merchant_type_selector);
            tempButton.setButtonDrawable(getResources().getDrawable(R.drawable.into_pieces_merchant_type_selector));
            tempButton.setTextColor(getResources().getColorStateList(R.drawable.into_txt_color_selector));
            tempButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            tempButton.setGravity(Gravity.CENTER);
            tempButton.setPadding(80, 0, 0, 0);
            tempButton.setText(list.get(i));
            tempButton.setTag(i);*/
            RadioButton tempButton = (RadioButton) View.inflate(mContext, R.layout.view_text_mark, null);
            tempButton.setId(i);
            tempButton.setText(problemTypes[i].typeName);
            tempButton.setTag(problemTypes[i].problemType);
            tempButton.setPadding(40, 20, 40, 20);
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.weight = 1;
            lp.setMargins(15, 10, 15, 10);// 设置间距
            tempButton.setLayoutParams(lp);
            ll_marklayout.addView(tempButton, lp);
        }
    }

    @Override
    protected void eventOnClick() {
        rl_addImage.setOnClickListener(this);
//        hv_sort.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        ll_marklayout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                RadioButton tv = (RadioButton) findViewById(checkedId);
                typeName = tv.getText().toString().trim();
                typeId = tv.getTag().toString().trim();
//                showToast("你选择了标签" +typeName+",typeId="+typeId);
            }
        });

        title_bar.setLeftOnClickListener(new TitleBar.LeftBtnOnClickListener() {
            @Override
            public void onLeftClick(View view) {
                showTipDialog();
            }
        });
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT,
                taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        ProblemApiServiceGrpc.ProblemApiServiceBlockingStub stub = ProblemApiServiceGrpc
                                .newBlockingStub(channel);
                        switch (taskId) {
                            case COMMIT_PROBLEM:
                                ProblemProto.ProblemRequest request = new ProblemProto.ProblemRequest();
                                request.userId = UserInfo.getUserInfo2SP().getUserNo();
                                request.userType = "1";
                                request.problemType = typeId;
//                                request.title = et_title.getEditContent();
                                request.title = "";
                                request.content = et_content.getText().toString().trim();
                                LogUtils.d("TAG", "problem : filePaths size = " + filePaths.size());
                                ProblemProto.ProblemFile[] problemFile = new ProblemProto.ProblemFile[filePaths.size()];
                                for (int i = 0; i < filePaths.size(); i++) {
                                    problemFile[i] = new ProblemProto.ProblemFile();
                                    problemFile[i].fileName = new File(filePaths.get(i)).getName();
                                    LogUtils.d("TAG", "problem : fileName = " + problemFile[i].fileName);
                                    problemFile[i].file = FileUtil.getByte(filePaths.get(i));
                                }
                                request.problemFile = problemFile;
                                ProblemProto.ProblemResponse response = stub.saveProblemInfo(request);
                                return response;
                            case PROBLEM_TYPE://问题类型
                                stub.withDeadlineAfter(5, TimeUnit.SECONDS);
                                ProblemProto.ProblemTypeRequest problemTypeRequest = new ProblemProto.ProblemTypeRequest();
                                ProblemProto.ProblemResponse problemResponse = stub.getProblemType(problemTypeRequest);
                                return problemResponse;
                        }
                        return null;

                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (result == null) {
                            showToast("请求失败");
                            return;
                        }
                        if (COMMIT_PROBLEM == taskId) {
                            ProblemProto.ProblemResponse response = (ProblemProto.ProblemResponse) result;
                            if (!response.resMsg.status) {
                                showToast(response.resMsg.msg);
                            } else {
                                showToast(response.resMsg.msg);
                                finish();
                            }
                        } else if (PROBLEM_TYPE == taskId) {
                            ProblemProto.ProblemResponse response = (ProblemProto.ProblemResponse) result;
                            ProblemProto.ProblemTypeMsg[] problemTypes = response.problemTypeMsg;
                            initMarksView(problemTypes);
//                            for(int i = 0; i < problemTypes.length; i ++){
//                                CustomChooseView chooseView = new CustomChooseView(mContext);
//                                chooseView.setTypeId(problemTypes[i].problemType);
//                                chooseView.setTitle(problemTypes[i].typeName);
//                                chooseView.setTag(i);
//                                chooseView.setOnClickListener(this);
//                                layout_content.addView(chooseView);
//                            }
//                            initData();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_add_image:
                i++;
                setNowPath("img" + i);
                selectAlbum();
                break;
//            case R.id.hv_problem_sort:
//                Bundle bundle = new Bundle();
//                bundle.putString(Constant.INTENT_FLAG, Constant.PROBLEM_TYPE);
//                bundle.putBoolean("isSingle", true);
//                goActivityForResult(DeviceTypeActivity.class, bundle, Constant.RequestCode.problem_type);
//                break;
            case R.id.btn_confirm:
                if (TextUtils.isEmpty(typeName)) {
                    showToast("请选择问题类型");
                    return;
                }
//                if (TextUtils.isEmpty(et_title.getEditContent())) {
//                    showToast("请填写问题标题");
//                    return;
//                }
                if (TextUtils.isEmpty(et_content.getText())) {
                    showToast("请填写问题内容");
                    return;
                }
                sendHttpRequest(COMMIT_PROBLEM);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Constant.RequestCode.problem_type) {
            typeName = data.getStringExtra("type_name");
            typeId = data.getStringExtra("problem_type");
//            hv_sort.setRightText(typeName);
        }
    }

    @Override
    protected String getPhotoPath() {
        return "eeepay_v2";
    }

    @Override
    protected void selectPhotoPathResult(File imgFile, Bitmap bitmap) {
        filePaths.add(imgFile.getAbsolutePath());
        DeleteImageView div = new DeleteImageView(mContext);
        div.setOnDeleteClickListener(this);
        div.setTag(imgFile.getAbsolutePath());
        ViewGroup.LayoutParams params1 = rl_addImage.getLayoutParams();
        div.setLayoutParams(params1);
        div.setImageViewBitmap(BitmapUtils.createBitmap(this, Uri.fromFile(imgFile), imgFile));
        fLayout_img.addView(div, 0);

    }

    @Override
    public void onDelete(String tag) {
        fLayout_img.removeView(fLayout_img.findViewWithTag(tag));
        filePaths.remove(tag);
        File file = new File(tag);
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    /**
     * 返回时；给出温馨提示一下
     */
    private void showTipDialog() {
        if (exitDialog == null) {

            exitDialog = DialogUtil.getDoubleCustomDialog(mContext, "温馨提醒", "您要放弃本次填写的内容吗？",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
        }
        if (!exitDialog.isShowing()) {

            exitDialog.show();
        }
    }
}
